//
//  NSString+Help.m
//  HDFramework
//
//  Created by haidong on 2016/10/13.
//  Copyright © 2016年 haidong. All rights reserved.
//

#import "NSString+Help.h"

@implementation NSString (Help)

+ (BOOL)checkTelNumber:(NSString *)telNumberStr {
    NSString *phoneRegex = @"^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *tempPhone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [tempPhone evaluateWithObject:telNumberStr];
    
//    /**
//     * 手机号码
//     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     * 联通：130,131,132,152,155,156,185,186
//     * 电信：133,1349,153,180,189
//     */
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
//    /**
//     10         * 中国移动：China Mobile
//     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     12         */
//    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
//    /**
//     15         * 中国联通：China Unicom
//     16         * 130,131,132,152,155,156,185,186
//     17         */
//    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
//    /**
//     20         * 中国电信：China Telecom
//     21         * 133,1349,153,180,189
//     22         */
//    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
//    /**
//     25         * 大陆地区固话及小灵通
//     26         * 区号：010,020,021,022,023,024,025,027,028,029
//     27         * 号码：七位或八位
//     28         */
//    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
//    
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//    
//    if (([regextestmobile evaluateWithObject:telNumberStr] == YES)
//        || ([regextestcm evaluateWithObject:telNumberStr] == YES)
//        || ([regextestct evaluateWithObject:telNumberStr] == YES)
//        || ([regextestcu evaluateWithObject:telNumberStr] == YES))
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
}

+ (BOOL)checkEmail:(NSString *)emailStr {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *tempEmail = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [tempEmail evaluateWithObject:emailStr];
}

+ (BOOL)checkIdCard:(NSString *)idCardStr {
    NSString *emailRegex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|[X|x])$";
    NSPredicate *tempPassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [tempPassword evaluateWithObject:idCardStr];
}

+ (BOOL)checkURL:(NSString *)urlStr {
    NSString *pattern =@"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [pred evaluateWithObject:urlStr];
}

+ (BOOL)checkIsChinese:(NSString *)chineseStr {
    NSString *match = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHS %@", match];
    return [predicate evaluateWithObject:chineseStr];
}

- (BOOL)checkIncludeChinese:(NSString *)str {
    for(int i=0; i< [self length];i++) {
        int a =[self characterAtIndex:i];
        if( a >0x4e00&& a <0x9fff){
            return YES;
        }
    }
    return NO;
}

- (BOOL)checkIsContainEmoji:(NSString *)str {
    __block BOOL returnValue =NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        if (0xd800) {
            if (0xd800 <= hs && hs <= 0xdbff) {
                if (substring.length > 1) {
                    const unichar ls = [substring characterAtIndex:1];
                    const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                    if (0x1d000 <= uc && uc <= 0x1f77f) {
                        returnValue =YES;
                    }
                }
            }else if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                if (ls == 0x20e3) {
                    returnValue =YES;
                }
            }else {
                // non surrogate
                if (0x2100 <= hs && hs <= 0x27ff) {
                    returnValue =YES;
                }else if (0x2B05 <= hs && hs <= 0x2b07) {
                    returnValue =YES;
                }else if (0x2934 <= hs && hs <= 0x2935) {
                    returnValue =YES;
                }else if (0x3297 <= hs && hs <= 0x3299) {
                    returnValue =YES;
                }else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                    returnValue =YES;
                }
            }
        }
        // ghd add 系统键盘文字表情不能检测出，通过判断长度检测
        if (substringRange.length > 1) {
            returnValue = YES;
        }
    }];
    return returnValue;
}

+ (NSString *)intTimeToDate:(long long)totalTime format:(NSString *)formatStr {
//    NSString *timeStamp2 = [NSString stringWithFormat:@"%lld",totalTime];
//    long long int date1 = (long long int)[timeStamp2 intValue];
    
//    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:totalTime];

    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:totalTime];
    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    
    if (formatStr && ![formatStr isEqualToString:@""]) {
        [formatter setDateFormat:formatStr];
    } else {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    }
    
    NSString *time = [formatter stringFromDate:date];
    return time;
    /*
     NSTimeZone *timeZone = [[NSTimeZone alloc] init];
     timeZone = [NSTimeZone systemTimeZone];//获取本地时区
     NSTimeInterval interval = [timeZone secondsFromGMT];
     NSDate *localDate = [date2 dateByAddingTimeInterval:interval];//localDate
     
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
     [dateFormatter setTimeZone:localTimeZone];
     
     //    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
     //    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
     
     
     
     if (formatStr && ![formatStr isEqualToString:@""]) {
     [dateFormatter setDateFormat:formatStr];
     } else {
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
     }
     NSString *str = [dateFormatter stringFromDate:localDate];
     
     return str;
     */

    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    
//    if (formatStr && ![formatStr isEqualToString:@""]) {
//        [dateFormatter setDateFormat:formatStr];
//    } else {
//        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    }
//    NSString *str = [dateFormatter stringFromDate:date2];
//    
//    return str;
}

+ (NSString *)intTimeToCountDown:(long long)totalTime {
    
    // 当前时间 date
    NSDate *currentDate = [NSDate date];
    NSTimeInterval currentInterval = [currentDate timeIntervalSince1970];
    
    NSTimeInterval futureInterval = currentInterval + totalTime;
    
    NSDate *futureDate = [NSDate dateWithTimeIntervalSince1970:futureInterval];
    
    // 日历对象 （方便比较两个日期之间的差距）
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // NSCalendarUnit 枚举代表想获得哪些差值 NSCalendarUnitYear 年 NSCalendarUnitWeekOfMonth 月
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *cmps = [calendar components:unit fromDate:currentDate toDate:futureDate options:0];
    
    // 获得某个时间的年月日时分秒
    
    //        NSDateComponents *createDateCmps = [calendar components:unit fromDate:DRstartDate];
    
    //        NSDateComponents *nowCmps = [calendar components:unit fromDate:DRendDate];
    
    NSLog(@"剩余%ld天,%ld小时%ld分", cmps.day ,cmps.hour, cmps.minute);
    
    NSLog(@"相差%ld小时",cmps.hour);
    
    return [NSString stringWithFormat:@"%ld天%ld小时%ld分%ld秒", cmps.day ,cmps.hour, cmps.minute, cmps.second];
}

+ (BOOL)checkPureNumber:(NSString *)str {
    NSScanner *scan = [NSScanner scannerWithString:str];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

- (NSString *)removeHTML {
    NSScanner *theScanner;
    NSString *text = nil;
    NSString * htmlStr = self;
    theScanner = [NSScanner scannerWithString:self];
    while ([theScanner isAtEnd] == NO) {
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        [theScanner scanUpToString:@">" intoString:&text] ;
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@" "];
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    }
    return htmlStr;
}

+ (NSString *)dataToJsonString:(id)object {
    NSString *jsonStr = nil;
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
    if (!data) {
//        DMLog(@"%@", [error localizedDescription]);
        NSLog(@"%@",[error localizedDescription]);
    } else {
        jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return jsonStr;
}

+ (CGFloat)heightWithText:(NSString *)text Font:(UIFont *)font andWidth:(CGFloat)width {
    CGSize textSize = CGSizeMake(width, CGFLOAT_MAX);
    //计算高度
    CGSize sizeWithFont = [text boundingRectWithSize:textSize options: NSStringDrawingUsesLineFragmentOrigin |
                           
                           NSStringDrawingUsesFontLeading|NSStringDrawingUsesDeviceMetrics attributes:@{NSFontAttributeName:font} context:nil].size;
    return ceil(sizeWithFont.height);
}

@end
